package com.yun.zhong.fu.sharecenter.rocketmq;


import com.yun.zhong.fu.sharecenter.dao.RocketLogDao;
import com.yun.zhong.fu.sharecenter.entity.RocketMqTranscationLog;
import com.yun.zhong.fu.sharecenter.service.ShareService;
import com.yun.zhong.fu.sharecenter.utils.SharedAuditDto;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

/**
 * @Author RenPu
 * @Date 2021/1/4 14:36
 * @Version 1.0
 * @Description: 配合编写分布式事务的事务类
 **/

@RocketMQTransactionListener(txProducerGroup = "test-add-bonus")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AddBonusTranscationListener implements RocketMQLocalTransactionListener {

    private final ShareService shareService;

    private final RocketLogDao rocketLogDao;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {

        MessageHeaders headers = message.getHeaders();
        Integer shareId = Integer.valueOf((String) headers.get("share_id"));
        String transcationId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);
        try {
            //如果验证成功，将此条消息设置为commit，可以供其他消费者进行消费
            this.shareService.auditByIdWithRocketMqLog(shareId, (SharedAuditDto) arg, transcationId);
//            this.shareService.auditByIdInDB(shareId,(SharedAuditDto) arg);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            //如果验证失败，将此条消息设置为ROLLBACK，此条消息进行回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }


    /**
     * 回查方法，为了避免突发事件导致事务的不一致性
     *
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        MessageHeaders headers = message.getHeaders();
        String transcationId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);

        RocketMqTranscationLog rocketMqTranscationLog = this.rocketLogDao.selectOneLog(transcationId);
        if (rocketMqTranscationLog != null) {
            //如果验证成功，将此条消息设置为commit，可以供其他消费者进行消费
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            //如果验证失败，将此条消息设置为ROLLBACK，此条消息进行回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
